package com.coollang.smartbra.fragment;

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.base.BaseFragment;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.bleutil.BleUtil;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.model.GoldAndActionModel;
import com.coollang.smartbra.model.LogInDataBean;
import com.coollang.smartbra.model.UserGoalAndStrengthModel;
import com.coollang.smartbra.presenter.PersonalFragmentPresenter;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.ImageLoader;
import com.coollang.smartbra.utils.PreferencesUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.utils.Utils;
import com.coollang.smartbra.views.pulltorefresh.PullToRefreshLayout;
import com.facebook.drawee.view.SimpleDraweeView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import eightbitlab.com.blurview.BlurView;
import eightbitlab.com.blurview.RenderScriptBlur;

/**
 * 我的页面
 */
public class PersonalFragment extends BaseFragment {
    @BindView(R.id.blurView)
    BlurView blurView;
    @BindView(R.id.iv_per_bg)
    SimpleDraweeView perBg;
    @BindView(R.id.iv_userhead)
    SimpleDraweeView ivUserhead;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.iv_sex)
    ImageView ivSex;
    @BindView(R.id.tv_news)
    TextView mTvNews;
    @BindView(R.id.rl_device_disconnect)
    RelativeLayout mRlDeviceDisconnect;
    @BindView(R.id.rl_device_connect)
    RelativeLayout mRlDeviceConnect;
    @BindView(R.id.device_name)
    TextView mTvDeviceName;
    @BindView(R.id.device_state)
    TextView mTvDeviceState;
    @BindView(R.id.tv_u_money)
    TextView mTvUMoney;

    @BindView(R.id.tv_goal_level)
    TextView mTvGoalLevel;
    @BindView(R.id.tv_strength_level)
    TextView mTvStrengthLevel;
    @BindView(R.id.tv_go_game)
    TextView mTvGoGame;

    @BindView(R.id.pulltorefreshlayout)
    PullToRefreshLayout mPullToRefreshLayout;

    private View view;

    private PersonalFragmentPresenter mFragmentPresenter;

    @Override
    public View inflateView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.fragment_personal, null, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void initView(View view) {
        initBlur();
        mPullToRefreshLayout.setIsEnabledRefreshAndReload(false);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        boolean hasNewVersion = PreferencesUtils.getBoolean(UIUtils.getContext(), "hasNewVersion");

        if (hasNewVersion && MyApplication.getApplication().isConnected) {
            // 有更新版本
            mTvNews.setVisibility(View.VISIBLE);
        } else {
            // 没有更新版本
            mTvNews.setVisibility(View.GONE);
        }
    }

    @Override
    public void initData() {
        mFragmentPresenter = new PersonalFragmentPresenter(this);
        GoldAndActionModel model = mFragmentPresenter.queryGoldAndAction();
        mTvUMoney.setText(model.getCoin() + "");
    }

    @Override
    public void onResume() {
        super.onResume();
        setTopUserInfo();
        checkUserIsBindDevice();
        queryGoalAndStrength();

        // 判断手机上是否有游戏app
        boolean avilible = Utils.isAvilible(getContext(), Constants.GAME_PKG);
        if (avilible) {
            mTvGoGame.setText("进入");
        } else {
            mTvGoGame.setText("下载");
        }
    }

    private void queryGoalAndStrength() {
        UserGoalAndStrengthModel model = mFragmentPresenter.queryGoalAndStrength();
        mTvGoalLevel.setText(getActionLevel(model.getGoal()));
        mTvStrengthLevel.setText(getActionLevel(model.getStrength()));
    }

    private String getActionLevel(int level) {
        String actionLevel = "";
        switch (level) {
            case 1:
                actionLevel = "入门";
                break;
            case 2:
                actionLevel = "初级";
                break;
            case 3:
                actionLevel = "中级";
                break;
            case 4:
                actionLevel = "高级";
                break;
            default:
                break;
        }
        return actionLevel;
    }

    // 验证用户是否绑定设备
    private void checkUserIsBindDevice() {
        if (mFragmentPresenter.isBindDevice()) {
            mRlDeviceDisconnect.setVisibility(View.GONE);
            mRlDeviceConnect.setVisibility(View.VISIBLE);
            mTvDeviceName.setText(MyApplication.getApplication().deviceName);
            // 判断是否连接
            if (MyApplication.getApplication().isConnected) {
                mTvDeviceState.setText("已连接");
            } else {
                mTvDeviceState.setText("未连接");
            }

        } else {
            mRlDeviceConnect.setVisibility(View.GONE);
            mRlDeviceDisconnect.setVisibility(View.VISIBLE);
        }
    }

    private void setTopUserInfo() {
        LogInDataBean mLogInDataBean = MyApplication.mLogInDataBean;
        ImageLoader.loadNetImageAsCircle(mLogInDataBean.getAvatar(), ivUserhead);
        ImageLoader.loadImage(Uri.parse(mLogInDataBean.getAvatar()), perBg);
        tvUsername.setText(mLogInDataBean.getNickname());

        if ("0".equals(mLogInDataBean.getGender())) {
            ivSex.setBackgroundResource(R.drawable.icon_female);
        } else {
            ivSex.setBackgroundResource(R.drawable.icon_male);
        }
    }

    private void initBlur() {
        float radius = 3f;
        View decorView = getActivity().getWindow().getDecorView();
        View rootView = decorView.findViewById(android.R.id.content);
        Drawable windowBackground = decorView.getBackground();
        blurView.setVisibility(View.VISIBLE);
        blurView.setupWith(rootView)
                .windowBackground(windowBackground)
                .blurAlgorithm(new RenderScriptBlur(this.getActivity(), true))
                .blurRadius(radius);
    }

    @OnClick({R.id.iv_userhead
            , R.id.btn_logout, R.id.rl_userdata
            , R.id.rl_about_hongjie, R.id.rl_share_app
            , R.id.rl_rd_envelopes, R.id.rl_device_disconnect
            , R.id.rl_device_connect, R.id.rl_action_difficulty
            , R.id.tv_go_game})
    public void onClick(View view) {
        switch (view.getId()) {
            // 跳到个人资料页面
            case R.id.iv_userhead:
                ActivitySwitcher.goToSelfInfoEdit(getActivity());
                break;
            // 退出登录
            case R.id.btn_logout:
                showLogoutDialog();
                break;
            // 个人资料
            case R.id.rl_userdata:
                ActivitySwitcher.goToSelfInfoEdit(getActivity());
                break;
            // 关于宏杰
            case R.id.rl_about_hongjie:
                ActivitySwitcher.goToAboutTeamActivity(getActivity());
                break;
            // 分享应用
            case R.id.rl_share_app:
                ActivitySwitcher.goToDifficulty(getActivity());
                break;
            case R.id.rl_action_difficulty:
                ActivitySwitcher.goToStrength(getActivity());
                break;
            // 红包页面
            case R.id.rl_rd_envelopes:
                ActivitySwitcher.goToUMoneyDetailsActivity(getActivity());
                break;
            case R.id.rl_device_disconnect:
                // 跳转搜索页面
                ActivitySwitcher.goSearchAct(getActivity());
                break;
            case R.id.rl_device_connect:
                // 跳转搜索页面
                ActivitySwitcher.goToDeviceInfo(getActivity());
                break;
            case R.id.tv_go_game:
                // 跳转游戏app
                String tvGoGame = mTvGoGame.getText().toString();
                if ("进入".equals(tvGoGame)) {
                    // 断开蓝牙连接 进入游戏
                    BleUtil.getInstance().disconnect();
                    mFragmentPresenter.goGame();
                } else {
                    ToastUtils.showToast("暂未开放");
                }
                break;
            default:
                break;
        }
    }

    private void showLogoutDialog() {
        AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setMessage("确定退出当前账号？");
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel1), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //dialog.dismiss();
            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.exit_app), new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {
                ImageLoader.clearCaches();
                MyApplication.getApplication().needLoginAgain();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button posiviveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }
}
